import axios from "axios";
import useUserStore from "@/store/modules/admin/user";
import { ElMessage } from "element-plus";

// axios基础封装
const request = axios.create({
  // 基础路径
  baseURL: import.meta.env.VITE_APP_BASE_API,
  // 超时时间
  timeout: import.meta.env.VITE_TIMEOUT,
});

// axios请求拦截器
request.interceptors.request.use((config) => {
  const userStore = useUserStore();
  if (userStore.token) {
    config.headers.token = userStore.token;
  }
  return config;
});

// axios响应式拦截器
request.interceptors.response.use(
  (response) => response.data,
  (error) => {
    let msg = "";
    let status = error.response.status;
    switch (status) {
      case 401:
        msg = "TOKEN过期";
        break;
      case 403:
        msg = "无权访问";
        break;
      case 404:
        msg = "请求地址错误";
        break;
      case 500:
        msg = "服务器错误";
        break;
      default:
        msg = "网络错误";
        break;
    }
    ElMessage({ type: "error", msg });
    return Promise.reject(error);
  }
);

export default request;
